package com.example.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.time.Instant;
import java.util.Date;

public class JwtUtil {

    // JWT 密钥
    private static final String SECRET_KEY = "secret";

    // JWT 过期时间（24小时）
    private static final long EXPIRATION_TIME = 24 * 60 * 60 * 1000L;

    // 生成 JWT
    public static String generateJwt(String subject) {

        Instant now = Instant.now();
        Instant expirationTime = now.plusSeconds(EXPIRATION_TIME / 1000);

//        Date now = new Date();
//        Date expirationDate = new Date(now.getTime() + EXPIRATION_TIME);

        return Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(Date.from(now))
                .setExpiration(Date.from(expirationTime))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
    }

    // 解析 JWT
    public static Claims parseJwt(String jwt) {
        return Jwts.parser()
                .setSigningKey(SECRET_KEY)
                .parseClaimsJws(jwt)
                .getBody();
    }
}
